package org.mtmi.ui.controls;

import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.mtmi.ui.GraphicUtil;
import org.mtmi.ui.layouts.LayoutData;
import org.mtmi.ui.scenes.COLOR;
import org.mtmi.ui.scenes.Scene;

/**
 * A button rendering different image depending on it state:
 * <ul>
 * <li> image up: when button is enabled, unchecked and released.
 * <li> image down: when button is enabled, unchecked and pressed.
 * <li> image checked up: when button is enabled, checked and released.
 * <li> image checked down: when button is enabled, checked and pressed.
 * </ul>
 *
 */
public class SButton extends AbstractButton
{
	
	private Image img_up, img_checked_up;
	private Image img_down, img_checked_down;
	
	public SButton( Scene scene, Image iup, Image idown, int _flags ) {
		super(scene, _flags);
		
		img_up = img_checked_up = iup;
		img_down = img_checked_down = idown;
		
		Rectangle r = img_up.getBounds();
		size.x = r.width;
		size.y = r.height;
	
		r = img_down.getBounds();
		size.x = Math.max( size.x, r.width );
		size.y = Math.max( size.y, r.height );
	}

	public void setCheckedImages( Image iup, Image idn ) {
		img_checked_up = iup;
		img_checked_down = idn;
	}
	
	@Override
	public Point computeSize( LayoutData l ) {
		return new Point( size.x, size.y );
	}

	@Override
	public boolean containsTouch(TouchControlEvent e) {
//TOOD: prendre en compte, en plus les pixels transparents ????		
		return GraphicUtil.rectContains( location, size, e.x, e.y );
	}

	@Override
	public void paint( GC gc ) {
		Image img;
		if( isTapped ) {
			if( isChecked ) {
				img = img_checked_down;
			} else {
				img = img_down;
			}
		} else {
			if( isChecked ) {
				img = img_checked_up;
			} else {
				img = img_up;
			}
		}
		
		int x = location.x, y = location.y;
		int w = size.x, h = size.y;
		if( w < 0 ) {
			x = x+w; w=-w; 
		}
		if( h < 0 ) {
			y = y+h; h=-h; 
		}
		Rectangle ri = img.getBounds();
		//int xi = location.x+(size.x-ri.width)/2;
		//int yi = location.y+(size.y-ri.height)/2;
		gc.drawImage( img, 0,0,ri.width,ri.height, x,y,w,h );
		
		if( !isEnabled() ) {
			gc.setBackground( COLOR.grey60 );
			gc.setAlpha( 180 );
			gc.fillRectangle( location.x,location.y,size.x,size.y );
			gc.setAlpha( 255 );
		}
	}
}
